package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     * @return
     */
    @PostMapping
    public Result<?> create(@RequestBody DishDTO dishDTO){
        dishService.create(dishDTO);
        String key = "dish_"+dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<?> delete(@RequestParam List<Long> ids){
        dishService.delete(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据id查询详情信息(回显)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishVO> queryById(@PathVariable Long id){
        DishVO dishVO = dishService.queryById(id);
        return Result.success(dishVO);
    }

    /**
     * 根据id修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public Result<?> update(@RequestBody DishDTO dishDTO){
        dishService.update(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 菜品起售、停售
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<?> updateStatus(Long id,@PathVariable Integer status){
        dishService.updateStatus(id,status);
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     *
     * @return
     */
    @GetMapping("/list")
    public Result list(Long categoryId){
        List<DishVO> dishVOList = dishService.list(categoryId);
        return Result.success(dishVOList);
    }

    /**
     * 清除缓存
     *
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
